package http

import (
	"bytes"
	"fmt"
	"net/http"
	"net/http/httputil"
	"strings"
	"sync"
)

type Request struct {
	*http.Request
	body []byte
	mu   sync.Mutex
}

// Bytes 转成字节,http协议,可直接通过tcp发送htp请求
func (this *Request) Bytes() ([]byte, error) {
	return httputil.DumpRequest(this.Request, true)
}

// AddHead 添加请求头
func (this *Request) AddHead(key, val string) {
	this.mu.Lock()
	defer this.mu.Unlock()
	this.Header.Add(key, val)
}

// GetBody 获取body内容,返回字节
func (this *Request) GetBody() []byte {
	return this.body
}

// GetBodyString 获取body内容,返回字符串
func (this *Request) GetBodyString() string {
	return string(this.body)
}

// String 实现系统接口,标准输出
func (this *Request) String() string {
	return fmt.Sprintf("%s\t%s%s%s",
		this.Method, this.URL, func() string {
			var s1, s2 string
			for i, v := range this.Request.Header {
				x := fmt.Sprintf("\n%s: %s", i, strings.Join(v, "; "))
				if strings.Contains(i, "Injoy") {
					s2 += x
				} else {
					s1 += x
				}
			}
			return s1 + s2
		}(), func() (s string) {
			if len(this.body) > 0 {
				s += "\n\n" + string(this.body)
			}
			return
		}())
}

// NewRequest 新建请求内容
func NewRequest(method, url string, body interface{}) (*Request, error) {
	bodyBytes := toBytes(body)
	request, err := http.NewRequest(method, url, bytes.NewBuffer(bodyBytes))
	if err != nil {
		return nil, err
	}
	data := &Request{
		Request: request,
		body:    bodyBytes,
	}
	return data, err
}
